<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Orm extends Model
{
    public $guarded = [];
    /**
     * 统一处理存储的资源类文件地址，如果存储路径非本地则补齐
     * @param $attribute_name 字段名称
     * @param $value 值
     */
    public function dealSetImageAttribute($attribute_name, $value)
    {
        if(!empty($value)) {
            if (is_string($value)){
                if(substr($value, 0, 4) != 'http') {
                    $default_disk = config('admin.upload.disk');
//                    if($default_disk != 'local'){
                        $this->attributes[$attribute_name] = config('filesystems.disks.'. $default_disk .'.url') . $value;

//                    } else {
//                        $this->attributes[$attribute_name] = $value;
//                    }
                } else {
                    $this->attributes[$attribute_name] = $value;
                }
//                if($attribute_name=='discover'){
//                    $imageInfo = getimagesize($this->attributes['discover']);
//                    $this->attributes['width']=$imageInfo[0];
//                    $this->attributes['height']=$imageInfo[1];
//                }
//                $this->attributes[$attribute_name] = UploadService::getImgAttribute($this->attributes[$attribute_name]);
            }elseif (is_array($value)){
                foreach ($value as $key => $val){
                    if (strpos($val, 'http') === false){
                        $default_disk = config('admin.upload.disk');
//                        if ($default_disk != 'local'){
                            $value[$key] = config('filesystems.disks.'. $default_disk .'.url') .$val;

//                        }
                    }
//                    $value[$key] = UploadService::getImgAttribute($value[$key]);
                }
                $this->attributes[$attribute_name] = json_encode($value);
            }

        } else {
            $this->attributes[$attribute_name] = "";
        }
    }

    /**
     * 默认返回日期格式
     * @return mixed
     */
    public function getCreatedAtAttribute()
    {
        if ((string)(int)$this->attributes['created_at'] == $this->attributes['created_at']){
            return date('Y-m-d H:i:s', $this->attributes['created_at']);
        }else{
            return $this->attributes['created_at'];
        }
    }

    /**
     * 默认返回日期格式
     * @return mixed
     */
    public function getUpdatedAtAttribute()
    {
        if ((string)(int)$this->attributes['updated_at'] == $this->attributes['updated_at']){
            return date('Y-m-d H:i:s', $this->attributes['updated_at']);
        }else{
            return $this->attributes['updated_at'];
        }
    }
}
